package com.yuxl.ai.spg.service;

import com.yuxl.ai.spg.entity.AiSpgSchema;
import com.yuxl.ai.spg.repository.AiSpgSchemaRepository;
import com.yuxl.common.auth.utils.JwtUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.LocalDateTime;

@Slf4j
@Service
public class AiSpgSchemaService {

    @Resource
    private AiSpgSchemaRepository aiSpgSchemaRepository;
    @Resource
    private JwtUtil jwtUtil;

    public Flux<AiSpgSchema> findAll() {
        return aiSpgSchemaRepository.findAll();
    }

    public Mono<AiSpgSchema> findById(Long id) {
        return aiSpgSchemaRepository.findById(id)
                .defaultIfEmpty(new AiSpgSchema());
    }

    public Mono<Void> deleteById(Long id) {
        return aiSpgSchemaRepository.deleteById(id);
    }

    public Mono<AiSpgSchema> create(AiSpgSchema entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setCreateBy(user.id());
                    entity.setUpdateBy(user.id());
                    entity.setCreateTime(LocalDateTime.now());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiSpgSchemaRepository.save(entity);
                });
    }

    public Mono<Integer> count(AiSpgSchema entity) {
        return aiSpgSchemaRepository.count(entity);
    }


    public Flux<AiSpgSchema> page(AiSpgSchema entity, int page, int size) {
        long offset = (long) (page - 1) * size;
        return aiSpgSchemaRepository.page(entity, size, offset);
    }


    public Flux<AiSpgSchema> list(AiSpgSchema entity) {
        return aiSpgSchemaRepository.list(entity);
    }

    public Mono<AiSpgSchema> updateById(AiSpgSchema entity) {
        return jwtUtil.getCurrentUser()
                .flatMap(user ->{
                    entity.setUpdateBy(user.id());
                    entity.setUpdateTime(LocalDateTime.now());
                    return aiSpgSchemaRepository.updateById(entity)
                            .flatMap(rows -> rows > 0 ? aiSpgSchemaRepository.findById(entity.getId()) : Mono.empty());
                });
    }
}
